package com.jiaojiao.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiaojiao.reggie.common.CustomException;
import com.jiaojiao.reggie.dto.SetmealDto;
import com.jiaojiao.reggie.entity.Setmeal;
import com.jiaojiao.reggie.entity.SetmealDish;
import com.jiaojiao.reggie.service.SetmealDishService;
import com.jiaojiao.reggie.mapper.SetmealMapper;
import com.jiaojiao.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    /**
     * 新增套餐，保存菜品和套餐的关联关系
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息，操作setmeal，插入操作
        this.save(setmealDto);
        //保存套餐和菜品关联关系，操作setmeal_dish，执行insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        //不能删除，抛出业务异常
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("套餐售卖中，不可以删除哟");
        }
        //先删除套餐数据
        this.removeByIds(ids);
        //删除关系表的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }

    @Override
    public void updateBatchById(List<Long> ids,int id) {
        List<Setmeal> list;
        list = ids.stream().map((item)->{
            Setmeal setmeal;
            setmeal = this.getById(item);
            setmeal.setStatus(id);
            return setmeal;
        }).collect(Collectors.toList());
        this.updateBatchById(list);
    }

}
